//
//  WJWOauthViewController.swift
//  SwiftWeibo
//
//  Created by 万嘉伟 on 16/7/21.
//  Copyright © 2016年 万嘉伟. All rights reserved.
//

import UIKit
import SVProgressHUD

class WJWOauthViewController: UIViewController {
    override func loadView() {
          self.view=webView
        //设置webView的代理
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor=UIColor.whiteColor()
        setupNavigaitonBar()
        //使用webview加载登录页面
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(client_id)&redirect_uri=\(redirect_uri)"
        let url=NSURL(string: urlString)
        let request=NSURLRequest(URL: url!)
        webView.loadRequest(request)
        //显示加载
        SVProgressHUD.setMinimumDismissTimeInterval(2)
        SVProgressHUD.showWithStatus("正在加载.....")
   
    }
    /**
     设置导航栏
     */
    private func setupNavigaitonBar() {
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        // title
        self.navigationItem.title = "登录"
    }
    /**
    *  自动填充账号密码,私有化
    */
    @objc private func autoFill(){
        let jsCode="document.getElementById('userId').value='18270828295';document.getElementById('passwd').value='godisagirl123'"
        //使用webview执行js代码
        webView.stringByEvaluatingJavaScriptFromString(jsCode)
    }
    /**
     关闭控制器
     */
    @objc private func close(){
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    /**
    *  懒加载网页
    */
    private lazy var webView: UIWebView = UIWebView()
}
//代理
extension WJWOauthViewController:UIWebViewDelegate{
    //webview加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    /**
    *  每当webView要去加载一个网页都会调用这个方法，ture加载，false不加载
    */
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let urlString=request.URL!.absoluteString
        print("加载的地址: \(urlString)")
        // 其他界面不需要拦截,只需要拦截授权回调地址
        if !urlString.hasPrefix(redirect_uri) {
            // 不是授权回调地址, 放过,去加载
            return true
        } else {
            // 是授权回调地址
            // 取消: http://www.baidu.com/?error_uri=%2Foauth2%2Fauthorize&error=access_
            // 授权: http://www.baidu.com/?code=8b222812bb9754a65e09f1d9bd4d5193

            // 区分 取消按钮 和 授权按钮,看?后面是否以code=开头
            let query = request.URL!.query!
            print("query: \(query)")
            // 判断query是否以code=开头
            let codeString = "code="
            if query.hasPrefix(codeString) {
                // 点击了授权
                print("点击了授权")
                // code=1d98d710a8288b23c8a0440bca0c846c
                // 截取code=后面那串字符串
                let nsQuery = query as NSString
                let code = nsQuery.substringFromIndex(codeString.characters.count)
                print("截取到的code = \(code)")
            } else {
                // 点击了取消
                print("点击了取消")
            }
            
            return false
        }
    }
}